package topicHandlers;

import groupManagement.ChatGroup;
import groupManagement.User;

import java.util.TimerTask;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import chat.LingvoChat;

/**
 * This class is responsible for:
 * <ol>
 * 	<li>adding the user to a group:
 * 	<ol>	
 * 		<li>If we are in the margin of 30 seconds we try to add if not exists 
 * 			to personsInGroup and userInGroup
 * 	</ol>
 * 	</li>
 * </ol>
 * 
 * <p>Received message types:</p>
 * <p>"Alive-"[username] - I'm alive message</p>
 * 	<p>"Joined-"[username] - join request, send back "Alive-"[username]</p>
 * 	<p>"Leave-"[username] - Leave request, delete user from group.</p>
 */
public class Control implements MessageListener{
	
	
	private String group;
	private String userName;
	private String lang;
	private ChatGroup chatGroup;

	public Control(String group,ChatGroup chatGroup,String userName,String lang)
	{
		this.group=group;
		this.chatGroup=chatGroup;
		this.userName=userName;
		this.lang=lang;
	}
	
	@Override
	public void onMessage(Message message) {
		
		String msg = null;

		try	{
			if (message instanceof TextMessage) {
				msg = ((TextMessage) message).getText();
			}
			else {
				System.out.println("Message of wrong type: "
						+ message.getClass().getName());
				return ;
			}
		} catch (JMSException e) {
			System.out.println("JMSException in onMessage(): " + e.toString());
		} catch (Throwable t) {
			System.out.println("Exception in onMessage():" + t.getMessage());
		}	
		parse(msg);
	}
	
	void parse(String msg){
		// parse and find what command should we execute
		int commandEnding = msg.indexOf("-");
		if(commandEnding==-1){
			//unrecognised command.
			return;
		}
		String command=msg.substring(0,commandEnding);
		String parameter=msg.substring(commandEnding+1);
		
		if(command.equals("alive")) {
			alive(parameter);
			
		} else if(command.equals("join")) {
			join(parameter);
		} else if(command.equals("leave")) {
			leave(parameter);
		} 
	}

	private void alive(String parameter) {
		String user,lang;
		int langEnding = parameter.indexOf("-");
		if(langEnding==-1){
			//unknown message
			return ;
		}
		lang=parameter.substring(0, langEnding);
		user=parameter.substring(langEnding+1);
		if(chatGroup.doYouHaveThisUser(user)==false){
			//add user to group f missed him on join request.
			chatGroup.addUser(user, lang);
		}
		else{
			User.userImAlive(user);
		}
	}
	
	private void join(String parameter) {
		alive(parameter);
		LingvoChat.publishMsg(group, "alive-"+lang+"-"+userName);
	}

	private void leave(String user) {
		if(chatGroup.doYouHaveThisUser(user)==true){
			chatGroup.removeUser(user);
		}
		
	}

}
